package me.firstapp.bts.service.impl;

import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import me.firstapp.bts.service.TopicJobService;
import me.firstapp.common.exception.StatusHouse;
import me.firstapp.common.json.ListObject;
import me.firstapp.common.json.SingleObject;
import me.firstapp.common.module.bbs.JsonTopic;
import me.firstapp.common.module.system.JsonApiClient;
import me.firstapp.spi.bbs.CollectionService;
import me.firstapp.spi.bbs.ReplyService;
import me.firstapp.spi.bbs.TopicService;
import me.firstapp.spi.system.ApiClientService;

@Service
public class TopicJobServiceImpl implements TopicJobService {

	private static Logger logger = LoggerFactory.getLogger(TopicJobService.class);

	@Autowired
	private TopicService topicService;

	@Autowired
	private ReplyService replyService;

	@Autowired
	private CollectionService collectionService;

	@Autowired
	private ApiClientService apiClientService;

	@Autowired
	private RedisTemplate<String, Object> redisTemplate;

	@Override
	public void updateTopics() {
		long start = System.currentTimeMillis();
		logger.info("............开始批处理更新话题...........");
		ListObject<JsonApiClient> clientsJson = apiClientService.findAll();
		if (clientsJson != null) {
			List<JsonApiClient> clients = clientsJson.getItems();
			if (clients != null && !clients.isEmpty()) {
				for (JsonApiClient client : clients) {
					// 只处理浏览过的话题
					@SuppressWarnings("unchecked")
					Map<Long, Long> topicViewCountsMap = (Map<Long, Long>) redisTemplate.opsForValue()
							.get("topicViewCountsMap" + client.getId());
					if (topicViewCountsMap != null) {
						Set<Long> topicIds = topicViewCountsMap.keySet();
						if (topicIds != null) {
							for (Long topicId : topicIds) {
								Long viewCounts = topicViewCountsMap.get(topicId);
								SingleObject<Long> replyResult = replyService.findTopicReplyCounts(topicId,
										client.getId());
								Long replyCounts = replyResult.getObject();
								SingleObject<Long> collectionResult = collectionService.findCollectionCounts(null,
										topicId, null, client.getId());
								Long collectionCounts = collectionResult.getObject();
								SingleObject<JsonTopic> result = topicService.updateTopic(topicId, null, null, null,
										viewCounts, replyCounts, collectionCounts, null, client.getId());
								if (StatusHouse.COMMON_STATUS_OK.getCode().equals(result.getCode())) {
									topicViewCountsMap.put(topicId, 0L);
								}
							}
							redisTemplate.opsForValue().set("topicViewCountsMap" + client.getId(), topicViewCountsMap);
						}
					}
				}
			}
		}
		logger.info(".............结束批处理更新话题.........耗时===》" + (System.currentTimeMillis() - start));
	}

}
